package com.example.androidmaze;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class GeneratingActivity extends Activity implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private static final String TAG = "GeneratingActivity";
	ProgressBar generatingBar;
	Maze maze;
	String strGeneration;
	String strOperation;
	String strLoad;
	View view;
	Thread progress;
	int difficulty;
	Singleton mazeInstance = Singleton.getInstance();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_generating);
		Bundle extras = getIntent().getExtras();

		if (extras != null) {
		    strGeneration = extras.getString("Generation");
		    strOperation = extras.getString("Operation");
		    strLoad = extras.getString("Load");
		    difficulty = extras.getInt("Difficulty");
		    Log.v(TAG, "Extras unpackaged");
		    Log.v(TAG, "strGeneration = " + strGeneration);
		    Log.v(TAG, "Difficulty: " + difficulty);
		}
		
//		// Show the Up button in the action bar.
//		setupActionBar();
//		Log.v(TAG, "Set up ActionBar");
		
		//begin maze
		if (strGeneration.equals("Backtracking")) {
			Log.v(TAG, "Calling Maze w Backtracking");
			//maze = new Maze(0, view, difficulty);
			mazeInstance.setMaze(0, view, difficulty);
		}
		else if (strGeneration.equals("Prim")) {
			Log.v(TAG, "Calling Maze w Prim");
			//maze = new Maze(1, view, difficulty);
			mazeInstance.setMaze(1, view, difficulty);
		}
		else if (strGeneration.equals("Eller")) {
			Log.v(TAG, "Calling Maze w Eller");
			//maze = new Maze(2, view, difficulty);
			mazeInstance.setMaze(2, view, difficulty);
		}
		else {
			//do nothing
		}
		//calling these in Singleton
//		Log.v(TAG, "Calling maze.init()");
//		mazeInstance.getMaze().init();
		
		
		Button btnStop = (Button)findViewById(R.id.buttonBack);
		
		generatingBar = (ProgressBar)findViewById(R.id.progressBar);
		generatingBar.setMax(99);
		
		progress = new Thread() {
			public void run() {
				int i;
				int prevI = 0;
				for (i=0; i<99; ) {
					if (i<=100) {
						i = Integer.parseInt(mazeInstance.getMaze().getPercentDone());
					}
					if (i == prevI && prevI > 0) {
						//Log.v(TAG, "prevI==i, finished generation");
						i = 99; //exits for loop, makes up for partiter fix in BSPBuilder
					}
					//Log.v(TAG, "i = " + i + ", percentDone = " + i + ", i<99: " + (i<99));
					try {
						progress.sleep(100);
						generatingBar.setProgress(i);
						prevI = i;
						
					} catch (InterruptedException e) {
						//Log.v(TAG, "Caught Interrupted exception");
						i+= 100;
						mazeInstance.getMaze().mazebuilder.buildThread.interrupt();
						e.printStackTrace();
					}
				}
				Log.v(TAG, "genBar.getProg: " + generatingBar.getProgress());
				if (generatingBar.getProgress() == 99) {
					Log.v(TAG, "Maze generation finished");
					Log.v(TAG, "To activity PlayActivity");
					Intent intent = new Intent(GeneratingActivity.this, PlayActivity.class);
					intent.putExtra("Operation", strOperation);
					startActivity(intent);
//					//package maze data for playActivity:
//					Bundle bundle = new Bundle();  
//					//mazecells:
//					int[][] mazecells = new int[maze.getWidth()][maze.getHeight()];
//					for (int j = 0; j<maze.getWidth(); j++) {
//						for (int k = 0; k<maze.getHeight(); k++) {
//							mazecells[j][k] = maze.mazecells.getCells(j, k);
//						}
//					}
//					bundle.putSerializable("mazecells", mazecells);
//					//seencells:
//					int[][] seencells = new int[maze.getWidth()][maze.getHeight()];
//					for (int j = 0; j<maze.getWidth(); j++) {
//						for (int k = 0; k<maze.getHeight(); k++) {
//							mazecells[j][k] = maze.seencells.getCells(j, k);
//						}
//					}
//					bundle.putSerializable("seencells", seencells);
//					//mazedists:
//					int[][] mazedists = new int[maze.mazedists.width][maze.mazedists.height];
//					mazedists = maze.mazedists.getDists();
//					bundle.putSerializable("mazedists", mazedists);
//					
//					intent.putExtras(bundle);
				}
			}
		};
		progress.start();
		
		btnStop.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v(TAG, "STOP clicked");
				Log.v(TAG, "To activity TitleActivity");
				progress.interrupt();
				interrupt();
				toTitle(v);
			}
		});
	}
		
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	public void toTitle(View view) {
		Intent intent = new Intent(this, TitleActivity.class);
		startActivity(intent);
	}
	
	public void toPlay(View view) {
		Intent intent = new Intent(this, PlayActivity.class);
		startActivity(intent);
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.generating, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	Intent intent = new Intent(this, TitleActivity.class);
	    	Log.v(TAG, "BACK button pressed");
			Log.v(TAG, "To activity TitleActivity");
			startActivity(intent);
	        return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}
	
	public void interrupt() {
		progress.interrupt();
	}

}
